package com.jsh.erp.service.printHistory;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.AccountHeadMapperEx;
import com.jsh.erp.datasource.mappers.DepotHeadMapperEx;
import com.jsh.erp.datasource.mappers.PrintHistoryMapper;
import com.jsh.erp.datasource.mappers.PrintHistoryMapperEx;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.accountHead.AccountHeadService;
import com.jsh.erp.service.dailyHead.DailyHeadService;
import com.jsh.erp.service.depotHead.DepotHeadService;
import com.jsh.erp.service.functions.FunctionService;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.IdUtils;
import com.jsh.erp.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class PrintHistoryService {
    private Logger logger = LoggerFactory.getLogger(PrintHistoryService.class);

    @Resource
    private PrintHistoryMapper printHistoryMapper;
    @Resource
    private PrintHistoryMapperEx printHistoryMapperEx;
    @Resource
    private UserService userService;
    @Resource
    private LogService logService;
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private FunctionService functionService;
    @Resource
    private DepotHeadService depotHeadService;
    @Resource
    private AccountHeadService accountHeadService;
    @Resource
    private DailyHeadService dailyHeadService;

    public PrintHistory getPrintHistory(String id)throws Exception {
        PrintHistory result=null;
        try{
            result=printHistoryMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<PrintHistory> getPrintHistoryListByIds(String ids)throws Exception {
        List<String> idList = StringUtil.strToStringList(ids);
        List<PrintHistory> list = new ArrayList<>();
        try{
            PrintHistoryExample example = new PrintHistoryExample();
            example.createCriteria().andIdIn(idList);
            list = printHistoryMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<PrintHistory> getPrintHistory()throws Exception {
        PrintHistoryExample example = new PrintHistoryExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<PrintHistory> list=null;
        try{
            list=printHistoryMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<PrintHistory> select(String name, String type, int offset, int rows)throws Exception {
        List<PrintHistory> list=null;
//        try{
//            list=printHistoryMapperEx.selectByConditionPrintHistory(name, type, offset, rows);
//        }catch(Exception e){
//            JshException.readFail(logger, e, systemConfigService.getLanCode());
//        }
        return list;
    }

    public Long countPrintHistory(String name, String type)throws Exception {
        Long result=null;
//        try{
//            result=printHistoryMapperEx.countsByPrintHistory(name, type);
//        }catch(Exception e){
//            JshException.readFail(logger, e, systemConfigService.getLanCode());
//        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertPrintHistory(JSONObject obj, HttpServletRequest request)throws Exception {
        PrintHistory printHistory = JSONObject.parseObject(obj.toJSONString(), PrintHistory.class);
        printHistory.setUploadFlag("0");
        int result=0;
        try{
            result=printHistoryMapper.insertSelective(printHistory);
            logService.insertLog("打印历史",
                    BusinessConstants.LOG_OPERATION_TYPE_ADD + printHistory.getId(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updatePrintHistory(JSONObject obj, HttpServletRequest request)throws Exception {
        PrintHistory printHistory = JSONObject.parseObject(obj.toJSONString(), PrintHistory.class);
        printHistory.setUploadFlag("0");
        int result=0;
        try{
            result=printHistoryMapper.updateByPrimaryKeySelective(printHistory);
            logService.insertLog("打印历史",
                    BusinessConstants.LOG_OPERATION_TYPE_EDIT + printHistory.getId(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deletePrintHistory(String id, HttpServletRequest request)throws Exception {
        return batchDeletePrintHistoryByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeletePrintHistory(String ids, HttpServletRequest request) throws Exception{
        return batchDeletePrintHistoryByIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeletePrintHistoryByIds(String ids)throws Exception {
        int result =0;
//        String [] idArray=ids.split(",");
//        //记录日志
//        StringBuffer sb = new StringBuffer();
//        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
//        List<PrintHistory> list = getPrintHistoryListByIds(ids);
//        for(PrintHistory printHistory: list){
//            sb.append("[").append(printHistory.getName()).append("]");
//        }
//        logService.insertLog("经手人", sb.toString(),StringUtil.getRequest());
//        //删除经手人
//        try{
//            result=printHistoryMapperEx.batchDeletePrintHistoryByIds(idArray);
//        }catch(Exception e){
//            JshException.writeFail(logger, e, systemConfigService.getLanCode());
//        }
        return result;
    }

    public int checkIsNameExist(String id, String name) throws Exception{
        return 0;
    }

//    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
//    public void AddPrintHistory(JSONObject obj, HttpServletRequest request,String lanCode)throws Exception {
//        PrintHistoryVo printHistory = JSONObject.parseObject(obj.toJSONString(), PrintHistoryVo.class);
//        Integer custom11 = printHistory.getCustom11();
//        String functionId = printHistory.getFunctionId();
//        Function function = functionService.getFunction(functionId);
//        String printType = null;
//        if (function.getState() != null && !function.getState()) {
//            if (function.getParentNumber().equals("0301") || function.getId().equals("1828064519905814edba23a5c44729f58ca04e3b91525")) {
//                printType = "2";
//            } else {
//                printType = "1";
//            }
//        }
//        if ("2".equals(printType) && 1 == custom11){
//            List<PrintHistory> printHistories = printHistoryMapperEx.selectByFunctionId(function.getName(),
//                    printHistory.getPrintId(), function.getId(), printType,custom11);
//            if (printHistories != null && printHistories.size()>0){
//                DepotHead depotHead = depotHeadService.getDepotHeadById(printHistory.getPrintId());
//                throw new BusinessRunTimeException(ExceptionConstants.PRINT_HISTORY_EXIST_CODE,
//                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.PRINT_HISTORY_EXIST_MSG : ExceptionConstants.PRINT_HISTORY_EXIST_MSG_US,depotHead.getNumber()));
//            }
//            printHistory.setId(IdUtils.getUUID());
//            printHistory.setFunctionId(function.getId());
//            printHistory.setPrintType(printType);
//            printHistory.setCustom11(custom11);
//            printHistory.setPrintName(function.getName());
//            printHistory.setPrintStatus("1");
//            Date date=new Date();
//            printHistory.setPrintTime(date);
//            printHistory.setCreateTime(date);
//            printHistory.setUploadFlag("0");
//            try{
//                printHistoryMapper.insertSelective(printHistory);
//            }catch(Exception e){
//                JshException.writeFail(logger, e, systemConfigService.getLanCode());
//            }
//        }else {
//            String ids = printHistory.getPrintId();
//            List<String> idList = StringUtil.strToStringList(ids);
//            if (idList == null || idList.size() <= 0) {
//                throw new BusinessRunTimeException(ExceptionConstants.PRINT_HISTORY_EXIST_CODE,
//                        "zh".equals(lanCode) ? "打印id不能为空" :"The print id can't be empty");
//            }
//            for (String id : idList) {
//                PrintHistory history = new PrintHistory();
//                List<PrintHistory> printHistories = printHistoryMapperEx.selectByFunctionId(function.getName(),
//                        id, function.getId(), printType, custom11);
//                if (printHistories != null && printHistories.size() > 0) {
//                    DepotHead depotHead = depotHeadService.getDepotHeadById(id);
//                    throw new BusinessRunTimeException(ExceptionConstants.PRINT_HISTORY_EXIST_CODE,
//                    String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.PRINT_HISTORY_EXIST_MSG : ExceptionConstants.PRINT_HISTORY_EXIST_MSG_US,depotHead.getNumber()));
//
//                }
//                history.setId(IdUtils.getUUID());
//                history.setFunctionId(function.getId());
//                history.setPrintId(id);
//                history.setPrintType(printType);
//                history.setCustom11(custom11);
//                history.setPrintName(function.getName());
//                history.setPrintStatus("1");
//                Date date = new Date();
//                history.setPrintTime(date);
//                history.setCreateTime(date);
//                history.setUploadFlag("0");
//                try {
//                    printHistoryMapper.insertSelective(history);
//                } catch (Exception e) {
//                    JshException.writeFail(logger, e, systemConfigService.getLanCode());
//                }
//            }
//        }
//        logService.insertLog("打印历史",
//                BusinessConstants.LOG_OPERATION_TYPE_ADD +function.getName()+":"+ printHistory.getId()+"，类型（1-列表 2-明细）"+custom11, request);
//    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void AddPrintHistory(JSONObject obj, HttpServletRequest request,String lanCode)throws Exception {
        PrintHistoryVo printHistory = JSONObject.parseObject(obj.toJSONString(), PrintHistoryVo.class);

        if (StringUtil.isEmpty(printHistory.getPrintId())) {
            throw new BusinessRunTimeException(ExceptionConstants.PRINT_HISTORY_EXIST_CODE,
                    "zh".equals(lanCode) ? "打印id不能为空" : "The print id can't be empty");
        }
        if (!printHistory.getFlag()){
            List<PrintHistory> printHistories = printHistoryMapperEx.selectByFunctionId(printHistory.getPrintName(),
                    printHistory.getPrintId(), printHistory.getCustom1());
            if (printHistories != null && printHistories.size() > 0) {
                String number=null;
                if (printHistory.getCustom11() !=null){
                    Integer custom11 = printHistory.getCustom11();
                    switch (custom11) {
                        case 1:
                            DepotHead depotHead = depotHeadService.getDepotHeadById(printHistory.getPrintId());
                            number = depotHead.getNumber();
                            break;
                        case 2:
                            AccountHead accountHead = accountHeadService.getAccountHead(printHistory.getPrintId());
                            number = accountHead.getNumber();
                            break;
//                        case 3:
//                            DailyHead dailyHead = dailyHeadService.getDailyHead(printHistory.getPrintId());
//                            number = dailyHead.getNumber();
//                            break;
                    }
                }

                throw new BusinessRunTimeException(ExceptionConstants.PRINT_HISTORY_EXIST_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.PRINT_HISTORY_EXIST_MSG : ExceptionConstants.PRINT_HISTORY_EXIST_MSG_US, number));
            }
        }
        printHistory.setId(IdUtils.getUUID());
//        printHistory.setFunctionId(function.getId());
//        printHistory.setPrintType(printType);
//        printHistory.setCustom11(custom11);
        printHistory.setPrintStatus("1");
        Date date = new Date();
        printHistory.setPrintTime(date);
        printHistory.setCreateTime(date);
        printHistory.setUploadFlag("0");
        try {
            printHistoryMapper.insertSelective(printHistory);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        logService.insertLog("打印历史",
                BusinessConstants.LOG_OPERATION_TYPE_ADD +printHistory.getPrintName()+":"+ printHistory.getId(), request);
    }
}
